﻿using BUGCOME.Auth.Api.Model.Auth;
using BUGCOME.Infrastructure;
using BUGCOME.Infrastructure.Cache;
using BUGCOME.Infrastructure.Extensions;
using BUGCOME.Model;
using BUGCOME.Model.Auth;
using BUGCOME.Model.Auth.dto;
using BUGCOME.Model.Common;
using BUGCOME.Model.Logs;
using BUGCOME.Service.Auth.IServices;
using BUGCOME.Service.Common.IServices;
using BUGCOME.Service.Logs.IServices;
using BUGCOME.ServiceCore.Filters;
using BUGCOME.ServiceCore.Services.IServices;
using Lazy.Captcha.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using SqlSugar;

namespace BUGCOME.Auth.Api.Controllers
{
    /// <summary>
    /// 授权认证API控制器
    /// 处理用户登录、注册、验证码、密码管理等认证相关功能
    /// 提供多种认证方式：账号密码登录、手机号登录、扫码登录等
    /// </summary>
    [Route("authapi/[controller]/[action]")]
    [ApiController]
    [ApiExplorerSettings(GroupName = "auth")]
    public class AuthController : BaseController
    {
        // 依赖注入的服务字段（已添加详细注释）
        private readonly IUserBaseService userBaseService;            // 用户基础信息服务，用于处理用户注册、登录、注销等基础操作
        private readonly ISysConfigService sysConfigService;          // 系统配置服务，用于获取系统参数（如验证码开关、密码策略等）
        private readonly ICaptcha captcha;                            // 验证码服务，负责生成图形验证码及验证逻辑
        private readonly ILoginService loginService;                  // 登录服务，处理账号密码登录、手机号登录等业务流程
        private readonly IRoleService roleService;                    // 角色服务，用于查询用户角色信息及角色权限
        private readonly IPermissionService permissionService;        // 权限服务，提供菜单权限、数据权限的校验功能
        private readonly ISmsCodeLogService smsCodeLogService;        // 短信验证码日志服务，记录和验证短信验证码发送情况
        private OptionsSetting optionsSetting;
        /// <summary>
        /// 构造函数，通过依赖注入初始化所需服务
        /// </summary>
        /// <param name="userBaseService">用户基础信息服务接口（注入用户基础信息管理实现类）</param>
        /// <param name="sysConfigService">系统配置服务接口（注入系统参数管理实现类）</param>
        /// <param name="captcha">验证码服务接口（注入图形验证码实现类）</param>
        /// <param name="loginService">登录服务接口（注入登录业务实现类）</param>
        /// <param name="roleService">角色服务接口（注入角色管理实现类）</param>
        /// <param name="permissionService">权限服务接口（注入权限校验实现类）</param>
        /// <param name="smsCodeLogService">短信验证码日志服务接口（注入短信验证码日志管理实现类）</param>
        /// <param name="optionsSetting">应用配置选项</param>
        /// <remarks>
        /// 依赖注入遵循原则：
        /// 1. 使用接口注入实现松耦合
        /// 2. 所有服务均为Scoped生命周期
        /// 3. 服务间职责清晰，避免循环依赖
        /// 4. 配置信息通过IOptions模式注入
        /// </remarks>
        public AuthController(
            IUserBaseService userBaseService,
            ISysConfigService sysConfigService,
            ICaptcha captcha,
            ILoginService loginService,
            IRoleService roleService,
            IPermissionService permissionService,
            ISmsCodeLogService smsCodeLogService,
            IOptions<OptionsSetting> optionsSetting)
        {
            this.userBaseService = userBaseService;
            this.sysConfigService = sysConfigService;
            this.captcha = captcha;
            this.loginService = loginService;
            this.roleService = roleService;
            this.permissionService = permissionService;
            this.smsCodeLogService = smsCodeLogService;
            this.optionsSetting = optionsSetting.Value;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        [Verify]
        [HttpGet]
        public async Task<IActionResult> GetUserInfo()
        {
            long userid = HttpContext.GetUId();
            var user = await userBaseService.SelectUserByIdAsync(userid);
            if (user == null)
            {
                return ToResponse(ApiResult.Error("用户已不存在，刷新一下！"));
            }
            //前端校验按钮权限使用
            //角色集合 eg: admin,yunying,common
            List<string> roles = await permissionService.GetRolePermissionAsync(user);
            //权限集合 eg *:*:*,admin:user:list
            List<string> permissions = await permissionService.GetMenuPermissionAsync(user);
            user.Password = string.Empty;
            return Success(new { user = user.Adapt<UserBaseDto>(), roles, permissions });
        }

        #region 注册

        /// <summary>
        /// 获取手机号注册验证码接口
        /// </summary>
        /// <param name="dto">包含手机号和用户类型的请求参数</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public async Task<IActionResult> GetMobileCode([FromBody] MobileCodeDto dto)
        {
            // 校验用户类型
            List<string> userTypes = new List<string>() { "1", "2", "3" };
            if (!userTypes.Contains(dto.UserType))
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "注册失败，用户类型错误");
            }

            // 检查手机号是否已存在
            bool isExist = await loginService.CheckUserMobileIsExistAsync(dto);
            if (isExist)
            {
                return ToResponse(ApiResult.Error("当前手机号已存在"));
            }
            // 检查短信服务配置
            MobileOptions? mobileOptions = optionsSetting.MobileOptions.Find(x => x.SignName == "阿里云短信测试");
            if (mobileOptions == null || string.IsNullOrEmpty(mobileOptions.SignName))
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "请先配置短信服务信息");
            }

            // 生成随机验证码并发送短信
            string random = Tools.GetRandomString(6, true, false, false, false, "");
            MobileHelper mobileHelper = new(mobileOptions);
            List<string> values = new List<string>() { random };
            AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsResponse resp = mobileHelper.SendMobile(dto.Mobile, values);

            // 处理短信发送结果
            if (resp.StatusCode == 200)
            {
                if (resp.Body.Code == "OK")
                {
                    // 缓存验证码（手机号+用户类型作为键）
                    CacheService.SetPhoneCode(dto.Mobile + "_" + dto.UserType, random);
                    return ToResponse(ApiResult.Success("获取验证码成功！"));
                }
                else
                {
                    return ToResponse(ApiResult.Error("获取验证码失败！,错误消息：" + resp.Body.Message));
                }
            }
            else
            {
                return ToResponse(ApiResult.Error("获取验证码失败！"));
            }
        }

        /// <summary>
        /// 账号注册接口
        /// </summary>
        /// <param name="dto">包含注册信息的请求参数</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        [AllowAnonymous]
        [Log(Title = "注册", BusinessType = BusinessType.INSERT)]
        public async Task<IActionResult> Register([FromBody] RegisterDto dto)
        {
            // 校验用户类型
            List<string> userTypes = new List<string>() { "1", "2", "3" };
            if (!userTypes.Contains(dto.UserType))
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "注册失败，用户类型错误");
            }

            // 检查注册功能是否开启
            if (dto.UserType == "2")
            {
                SysConfig config = await sysConfigService.GetSysConfigByKeyAsync("sys.account.register");
                if (config?.ConfigValue != "True")
                {
                    return ToResponse(ResultCode.CUSTOM_ERROR, "当前系统没有开启注册功能！");
                }
            }

            // 校验短信验证码
            if (!CacheService.CheckPhoneCode(dto.Username + "_" + dto.UserType, dto.Code))
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "注册失败，验证码错误");
            }
            else
            {
                CacheService.RemovePhoneCode(dto.Username + "_" + dto.UserType);  // 验证成功后移除验证码
            }

            // 校验密码一致性
            if (!dto.ConfirmPassword.Equals(dto.Password))
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "注册失败，密码和确认密码不一致");
            }

            // 设置注册IP
            dto.UserIP = HttpContext.GetClientUserIp();

            // 执行注册逻辑
            var result = await userBaseService.RegisterAsync(dto);

            return ToResponse(result);
        }

        #endregion

        #region 验证码登录

        /// <summary>
        /// 验证码登录接口
        /// </summary>
        /// <param name="dto">登录请求参数，包含用户名、密码、验证码等信息</param>
        /// <returns>包含JWT令牌的成功响应或错误信息</returns>
        [HttpPost]
        [Log(Title = "登录")]
        public async Task<IActionResult> Login([FromBody] LoginDto dto)
        {
            // 参数校验
            if (dto == null) { throw new CustomException("请求参数错误"); }

            //使用原有参数中的username和usertype检查锁定
            loginService.CheckLoginLock(dto.Username);

            // 获取客户端IP
            dto.LoginIP = HttpContextExtension.GetClientUserIp(HttpContext);

            // 校验验证码
            SysConfig sysConfig = await sysConfigService.GetSysConfigByKeyAsync("sys.account.captchaOnOff");
            if (sysConfig?.ConfigValue != "off" && !captcha.Validate(dto.Uuid, dto.Code))
            {
                loginService.RecordLoginFail(dto.Username);
                return ToResponse(ResultCode.CAPTCHA_ERROR, "验证码错误");
            }
            try
            {
                // 检查用户锁定状态
                loginService.CheckLockUser(dto.Username);

                // 获取登录位置信息
                string location = HttpContextExtension.GetIpInfo(dto.LoginIP);

                // 执行登录逻辑
                var user = await loginService.LoginAsync(dto, new UserLoginLog() { LoginLocation = location });

                // 获取用户角色和权限
                List<Role> roles = await roleService.SelectUserRoleListByUserIdAsync(user.Id);
                List<string> permissions = await permissionService.GetMenuPermissionAsync(user);
                // 构建登录用户模型并缓存权限
                TokenModel loginUser = new(user.Adapt<TokenModel>(), roles.Adapt<List<Roles>>());
                loginUser.UserId = user.Id;
                loginUser.ClientId = dto.ClientId;
                CacheService.SetUserPerms(GlobalConstant.UserPermKEY + user.Id, permissions);
                // 登录成功：重置失败次数（使用原有参数）
                loginService.ResetLoginFailCount(dto.Username);
                // 生成JWT令牌并返回
                return Success(JwtUtil.GenerateJwtToken(JwtUtil.AddClaims(loginUser)));
            }
            catch (CustomException ex)
            {
                // 登录失败：记录次数（使用原有参数）
                if (ex.Code == (int)ResultCode.LOGIN_ERROR ||
                    ex.Message.Contains("用户名或密码"))
                {
                    loginService.RecordLoginFail(dto.Username);
                }
                throw;
            }
        }

        /// <summary>
        /// 获取验证码图片接口
        /// </summary>
        /// <returns>包含验证码状态、唯一标识和图片Base64数据的响应</returns>
        [HttpGet]
        public async Task<IActionResult> CaptchaImage()
        {
            // 生成唯一UUID用于标识验证码
            string uuid = Guid.NewGuid().ToString().Replace("-", "");

            // 异步获取验证码开关配置
            SysConfig sysConfig = await sysConfigService.GetSysConfigByKeyAsync("sys.account.captchaOnOff");
            var captchaOff = sysConfig?.ConfigValue ?? "0";

            // 生成验证码信息（包含图片和验证数据）
            var info = captcha.Generate(uuid, 60);  // 60秒有效期

            // 构建返回结果
            var obj = new CaptchaImageModel() { CaptchaOff = captchaOff, Uuid = uuid, Img = info.Base64 };
            //  var obj = new CaptchaImageModel() { CaptchaOff = captchaOff, Uuid = uuid, Img = JsonConvert.SerializeObject(info) };
            return Success(obj);
        }

        #endregion

        #region 手机号登录

        /// <summary>
        /// 发送手机验证码接口
        /// </summary>
        /// <param name="dto">包含手机号、发送类型等信息的请求参数</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        [Log(Title = "发送短息", BusinessType = BusinessType.INSERT)]
        public async Task<IActionResult> CheckMobile([FromBody] PhoneLoginDto dto)
        {
            // 获取客户端IP
            dto.LoginIP = HttpContextExtension.GetClientUserIp(HttpContext);
            var uid = HttpContext.GetUId();

            // 根据发送类型处理不同业务逻辑
            if (dto.SendType == 0)
            {
                // 检查手机号是否存在
                var info = await userBaseService.GetFirstAsync(f => f.Phone == dto.PhoneNum)
                    ?? throw new CustomException(ResultCode.CUSTOM_ERROR, "该手机号不存在", false);
                uid = info.Id;
            }
            if (dto.SendType == 1)
            {
                // 检查手机号是否已绑定
                if ((await userBaseService.CheckPhoneBindAsync(dto.PhoneNum)).Count > 0)
                {
                    return ToResponse(ResultCode.CUSTOM_ERROR, "手机号已绑定其他账号");
                }
            }

            // 记录短信发送日志
            string location = HttpContextExtension.GetIpInfo(dto.LoginIP);
            await smsCodeLogService.AddSmscodeLogAsync(new SmsCodeLog()
            {
                Id = uid,
                PhoneNum = dto.PhoneNum.ParseToLong(),
                SendType = dto.SendType,
                UserIP = dto.LoginIP,
                Location = location,
            });

            return Success(1);
        }

        /// <summary>
        /// 手机号登录接口
        /// </summary>
        /// <param name="loginBody">包含手机号、验证码等信息的请求参数</param>
        /// <returns>包含JWT令牌的成功响应或错误信息</returns>
        [HttpPost]
        [Log(Title = "手机号登录")]
        public async Task<IActionResult> PhoneLogin([FromBody] PhoneLoginDto loginBody)
        {
            // 参数校验
            if (loginBody == null) { throw new CustomException("请求参数错误"); }
            loginBody.LoginIP = HttpContextExtension.GetClientUserIp(HttpContext);

            // 校验短信验证码
            if (!CacheService.CheckPhoneCode(loginBody.PhoneNum, loginBody.PhoneCode))
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "短信验证码错误");
            }

            // 检查手机号是否存在
            var info = userBaseService.GetFirst(f => f.Phone == loginBody.PhoneNum)
                ?? throw new CustomException(ResultCode.CUSTOM_ERROR, "该手机号不存在", false);

            // 检查用户锁定状态
            loginService.CheckLockUser(info.UserName);

            // 获取登录位置信息
            string location = HttpContextExtension.GetIpInfo(loginBody.LoginIP);

            // 执行手机号登录逻辑
            var user = await loginService.PhoneLoginAsync(loginBody, new UserLoginLog() { LoginLocation = location }, info);

            // 获取用户角色和权限
            List<Role> roles = await roleService.SelectUserRoleListByUserIdAsync(user.Id);
            List<string> permissions = await permissionService.GetMenuPermissionAsync(user);

            // 构建登录用户模型并缓存权限
            TokenModel loginUser = new(user.Adapt<TokenModel>(), roles.Adapt<List<Roles>>());
            loginUser.UserId = user.Id;
            CacheService.SetUserPerms(GlobalConstant.UserPermKEY + user.Id, permissions);

            // 生成JWT令牌并返回
            return Success(JwtUtil.GenerateJwtToken(JwtUtil.AddClaims(loginUser)));
        }

        /// <summary>
        /// 手机号绑定接口
        /// </summary>
        /// <param name="loginBody">包含手机号、验证码等信息的请求参数</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        [Log(Title = "手机号绑定")]
        public async Task<IActionResult> PhoneBind([FromBody] PhoneLoginDto loginBody)
        {
            // 参数校验
            if (loginBody == null) { throw new CustomException("请求参数错误"); }
            loginBody.LoginIP = HttpContextExtension.GetClientUserIp(HttpContext);
            var uid = HttpContext.GetUId();

            // 校验短信验证码
            if (!CacheService.CheckPhoneCode(loginBody.PhoneNum, loginBody.PhoneCode))
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "短信验证码错误");
            }

            // 执行手机号绑定逻辑
            var result = await userBaseService.PhoneBindAsync(uid, loginBody.PhoneNum);
            return Success(result);
        }

        #endregion

        #region 二维码登录

        /// <summary>
        /// 生成登录二维码接口
        /// </summary>
        /// <param name="uuid">唯一标识</param>
        /// <param name="deviceId">设备标识</param>
        /// <returns>包含二维码状态、唯一标识和内容的响应</returns>
        [HttpGet]
        public IActionResult GenerateQrcode(string uuid, string deviceId)
        {
            // 生成状态标识并缓存
            var state = Guid.NewGuid().ToString();
            var dict = new Dictionary<string, object> { { "state", state } };
            CacheService.SetScanLogin(uuid, dict);

            // 构建二维码内容（包含UUID和设备ID）
            return Success(new
            {
                status = 1,
                state,
                uuid,
                codeContent = new { uuid, deviceId }
            });
        }

        /// <summary>
        /// 轮询检查扫码状态接口
        /// </summary>
        /// <param name="dto">包含UUID的请求参数</param>
        /// <returns>包含扫码状态和令牌的响应</returns>
        [HttpPost]
        [AllowAnonymous]
        public IActionResult VerifyScan([FromBody] ScanDto dto)
        {
            int status = -1;
            object token = string.Empty;

            // 检查扫码登录缓存
            if (CacheService.GetScanLogin(dto.Uuid) is Dictionary<string, object> str)
            {
                status = 0;
                str.TryGetValue("token", out token);

                // 检查扫码是否成功
                if (str.ContainsKey("status") && (string)str.GetValueOrDefault("status") == "success")
                {
                    status = 2;  // 扫码成功状态码
                    CacheService.RemoveScanLogin(dto.Uuid);  // 移除缓存
                }
            }

            return Success(new { status, token });
        }

        /// <summary>
        /// 移动端扫码登录接口
        /// </summary>
        /// <param name="dto">包含UUID的请求参数</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        [Log(Title = "扫码登录")]
        [Verify]
        public IActionResult ScanLogin([FromBody] ScanDto dto)
        {
            // 参数校验
            if (dto == null) { return ToResponse(ResultCode.CUSTOM_ERROR, "扫码失败"); }
            var name = App.HttpContext.GetName();

            // 检查用户锁定状态
            loginService.CheckLockUser(name);

            // 获取当前登录用户信息
            TokenModel tokenModel = JwtUtil.GetLoginUser(HttpContext);

            // 检查二维码是否有效并设置扫码结果
            if (CacheService.GetScanLogin(dto.Uuid) is not null)
            {
                Dictionary<string, object> dict = new()
                {
                    { "status", "success" },
                    { "token", JwtUtil.GenerateJwtToken(JwtUtil.AddClaims(tokenModel)) }
                };
                CacheService.SetScanLogin(dto.Uuid, dict);
                return Success(1);
            }

            return ToResponse(ResultCode.FAIL, "二维码已失效");
        }

        #endregion

        #region 修改密码

        /// <summary>
        /// 忘记密码流程初始化接口
        /// </summary>
        /// <param name="dto">包含手机号和用户类型的请求参数</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public async Task<IActionResult> Forget(MobileCodeDto dto)
        {
            // 校验用户类型
            List<string> userTypes = new List<string>() { "1", "2" };
            if (!userTypes.Contains(dto.UserType))
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "提交失败，用户类型错误");
            }

            // 检查用户是否存在
            UserBase userBase = await userBaseService.GetFirstAsync(u =>
                u.UserName == dto.Mobile && u.UserType == dto.UserType && u.DelFlag == 0);
            if (userBase == null)
            {
                return ToResponse(ApiResult.Error("手机号不存在"));
            }

            // 生成临时令牌并缓存（2分钟有效期）
            string guid = Guid.NewGuid().ToString().Replace("-", "");
            CacheHelper.SetCache(guid, dto.UserType + "_" + dto.Mobile, 2);
            return ToResponse(ApiResult.Success("提交成功", guid));
        }

        /// <summary>
        /// 忘记密码流程中获取手机验证码接口
        /// </summary>
        /// <param name="dto">包含临时令牌的请求参数</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public IActionResult EidtPwdGetMobileCode(ParmDto<string> dto)
        {
            // 校验参数
            if (dto == null || string.IsNullOrEmpty(dto.Value))
            {
                return ToResponse(ApiResult.Error("该链接已失效，无法获取验证码！"));
            }

            // 获取临时缓存信息
            string str = CacheHelper.GetCache<string>(dto.Value);
            if (string.IsNullOrEmpty(str))
            {
                return ToResponse(ApiResult.Error("该链接已失效，无法获取验证码！"));
            }

            // 解析缓存信息
            List<string> parms = str.Split('_').ToList();
            if (parms.Count != 2)
            {
                return ToResponse(ApiResult.Error("该链接已失效，无法获取验证码！"));
            }

            // 构建手机号和用户类型对象
            MobileCodeDto mobileCodeDto = new MobileCodeDto
            {
                Mobile = parms[1],
                UserType = parms[0]
            };

            // 检查短信服务配置
            MobileOptions? mobileOptions = optionsSetting.MobileOptions.Find(x => x.SignName == "阿里云短信测试");
            if (mobileOptions == null || string.IsNullOrEmpty(mobileOptions.SignName))
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "请先配置短信服务信息");
            }

            // 生成随机验证码并发送短信
            string random = Tools.GetRandomString(6, true, false, false, false, "");
            MobileHelper mobileHelper = new(mobileOptions);
            List<string> values = new List<string>() { random };
            AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsResponse resp = mobileHelper.SendMobile(mobileCodeDto.Mobile, values);

            // 处理短信发送结果
            if (resp.StatusCode == 200)
            {
                if (resp.Body.Code == "OK")
                {
                    // 缓存忘记密码验证码
                    CacheService.SetForgetPwd(mobileCodeDto.Mobile + "_" + mobileCodeDto.UserType, random);
                    return ToResponse(ApiResult.Success("获取验证码成功！"));
                }
                else
                {
                    return ToResponse(ApiResult.Error("获取验证码失败！,错误消息：" + resp.Body.Message));
                }
            }
            else
            {
                return ToResponse(ApiResult.Error("获取验证码失败！"));
            }
        }

        /// <summary>
        /// 通过手机验证码修改密码接口
        /// </summary>
        /// <param name="dto">包含新密码、确认密码和临时令牌的请求参数</param>
        /// <returns>操作结果：成功或失败的响应信息</returns>
        /// <remarks>
        /// 流程说明：
        /// 1. 验证新密码和确认密码是否一致
        /// 2. 从缓存中解析临时令牌获取用户标识
        /// 3. 根据标识查找目标用户
        /// 4. 加密新密码并更新到数据库
        /// 5. 密码修改成功后移除临时令牌
        /// </remarks>
        [HttpPost]
        public async Task<IActionResult> EidtPwd(EidtPwdDto dto)
        {
            // 验证新密码和确认密码是否一致
            if (!dto.ConfirmPassword.Equals(dto.Password))
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "修改密码失败，密码和确认密码不一致");
            }

            // 从缓存获取临时令牌对应的信息（格式：用户类型_手机号）
            string str = CacheHelper.GetCache<string>(dto.Token);
            List<string> parms = str.Split('_').ToList();

            // 验证缓存信息有效性
            if (parms.Count != 2)
            {
                return ToResponse(ApiResult.Error("该链接已失效，无法获取验证码！"));
            }

            // 解析缓存信息，构建用户查询条件
            MobileCodeDto mobileCodeDto = new MobileCodeDto
            {
                Mobile = parms[1],          // 手机号
                UserType = parms[0]         // 用户类型
            };

            // 根据手机号和用户类型查询有效用户
            UserBase userBase = await userBaseService.GetFirstAsync(u =>
                u.UserName == mobileCodeDto.Mobile &&    // 用户名匹配手机号
                u.UserType == mobileCodeDto.UserType &&  // 用户类型匹配
                u.DelFlag == 0);                         // 未删除的用户

            // 验证用户是否存在
            if (userBase == null)
            {
                return ToResponse(ApiResult.Error("修改密码失败！"));
            }

            // 使用MD5加密新密码（注意：建议使用更安全的加密算法）
            string pwd = NETCore.Encrypt.EncryptProvider.Md5(dto.Password);

            // 更新用户密码
            if (await userBaseService.ResetPwdAsync(userBase.Id, pwd) > 0)
            {
                CacheHelper.Remove(dto.Token);  // 密码修改成功后，移除临时令牌防止重复使用
                return Success(1);              // 返回成功响应
            }

            // 处理密码修改异常情况
            return ToResponse(ApiResult.Error("修改密码异常，请联系管理员"));
        }

        #endregion

        #region 注销

        /// <summary>
        /// 用户注销接口
        /// </summary>
        /// <returns>包含用户信息的成功响应</returns>
        [Log(Title = "注销")]
        [HttpPost]
        public async Task<IActionResult> LogOut()
        {
            // 获取当前用户信息
            var userid = HttpContext.GetUId();
            var name = HttpContext.GetName();

            // 异步移除用户权限缓存（使用Task.Run包装同步操作）
            await Task.Run(() =>
            {
                CacheService.RemoveUserPerms(GlobalConstant.UserPermKEY + userid);
            });

            return Success(new { name, id = userid });
        }

        #endregion
    }
}